package lib::Context;

# This file is part of noplagia.
#
# noplagia is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# noplagia is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# noplagia; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307 USA

use strict;
use warnings;
use Data::Dumper;
require Exporter;
our ($VERSION,@ISA,@EXPORT);

$VERSION = 0.01;
use constant CONFIG_FNAME => "/etc/noplagia.conf";
@ISA    = qw(Exporter);
@EXPORT = qw(
    &config
    &get_user_flags
    &get_dbh
    &get_session
    &get_current_user
    &set_conn_db
    &get_pref
    &get_prefs
    &get_flags
    &delete_user_flags;
    &get_users;
);

=head1 NAME

    lib::Context

=head1 SYNOPSIS

    use lib::Context;

=head1 DESCRIPTION

    Ce module lit le fichier de conf, et initialise le contexte d'execution
    du programme.

=head1 FUNCTIONS

=over 2

=cut

=item config

    $value = &config("config_variable");
    C<config_variable> doit etre une cle du fichier de configuration

=cut

sub config($) {
	my $var   = shift;
    my $value = undef;
    my $conf_file = $ENV{"NOPLAGIA_CONF"} || CONFIG_FNAME;
    open (CONF,"<",$conf_file) or die "can't read $conf_file: $!";
    while (<CONF>) {
        chomp;
        s/#.*//;            # Strip comments
        next if not length;
        next if /^\s*$/;    # Ignore blank lines

        # Look for a line of the form var = value
        next if not m/^\s*(\w*)\s*=\s*(.*)\s*$/;
        if ($1 eq $var){
            $value = $2;
            last if $value;
        }
    }
    close CONF;
    return $value;
}

=item set_conn_db

    &set_conn_db;
    Connection a la BDD.

=cut

sub set_conn_db() {
    use lib::DB::Main;
    my $connection_uri = "dbi:".config('dbms').":database=".config('database').";host=".config('host');
    $ENV{"NOPLAGIA_DB"} = lib::DB::Main->connect($connection_uri,config('user'),config('pass')) unless $ENV{"NOPLAGIA_DB"};
}

=item get_user_flags

    my $flags = &get_user_flags($user_id);
    retourne les flags de l'utilisateur courant.

=cut

sub get_user_flags($) {
    my $user_id = shift;
    my $schema  = &get_dbh;
    my $userflags = $schema->resultset('UserFlags')->search(
        {
            users => $user_id
        },
        {
            order_by => 'Nom DESC'
        }
    );
    my %flags;
    while(my $flag = $userflags->next){
        $flags{$flag->nom} = 1;
    }
    return \%flags;
}

=item get_current_user
    
    my $user = &get_current_user;
    print "user id is = $user->id";
    
    retourne les informations sur l'utilisateur courant
    
=cut

sub get_current_user() {
    my $user_id = &get_session->param('id');
    my $dbh     = &get_dbh;
    my $user = $dbh->resultset('Users')->find({ id=>$user_id });
    return $user;
}

=item get_dbh
    
    use lib::Context;
    my $dbh = &get_dbh;
    
    retourne le handler a la base de donnee
    
=cut

sub get_dbh() {
    return $ENV{"NOPLAGIA_DB"};
}

=item get_session

    use lib::Context;
    my $session = &get_session;

=cut

sub get_session() {
    return $ENV{"NOPLAGIA_SESSION"};
}

=item get_pref
    
    use lib::Context;
    my $pref  = get_pref('MaxRequest');
    
=cut

sub get_pref($){
    my $nom = shift;
    my $dbh = &get_dbh;
    my $value;
    my $pref = $dbh->resultset('Syspref')->find(
        {
            nom => $nom,
        }
    );
    eval{
        $value = $pref->value;
    };
    if($@){
        warn "Error when asking for $nom syspref !";
        return undef;
    }
    return $value;
}

=item get_prefs
    
    use lib::Context;
    my $prefs = get_prefs();
    while(my $pref = $prefs->next){
        print $pref->nom;
    }
    
    this function returns all syspref from the table 'Syspref'
    
=cut

sub get_prefs(){
    my $dbh = &get_dbh;
    return $dbh->resultset('Syspref')->search();
}

=item get_flags

    use lib::Context;
    my $flags = get_flags()
    while(my $flag = $flags->next){
        ...
    }
    
=cut

sub get_flags() {
    my $dbh  = &get_dbh;
    return $dbh->resultset('UserFlags')->search(
        {},
        { 
            group_by => 'nom',
            distinct => 1,
        }
    );
}

=item delete_user_flags

    delete_user_flags($user_id);
    delete all rows where user_id = $user_id

=cut

sub delete_user_flags($){
    my $user_id = shift;
    my $dbh = get_dbh();
    my $rows = $dbh->resultset('UserFlags')->search(
        {
            Users => $user_id,
        }
    );
    $rows->delete_all;
}

=item get_users

    my $users = get_users();
    while($user = $users->next){
        print $user->pseudo;
    }
    
=cut

sub get_users() {
    my $dbh = get_dbh();
    return $dbh->resultset('Users')->search({});
}

END { }
1;
__END__

=back

=head1 AUTEUR

    noplagia dev team

    http://noplagia.org

=cut
